import { isNil } from 'lodash'
import { useState } from 'react'

import { storage } from '@/utils/storage'

export function useStorage<V = any>(key: string): [V | null, React.Dispatch<React.SetStateAction<V | null>>]
export function useStorage<V = any>(key: string, defaults: V): [V, React.Dispatch<React.SetStateAction<V | null>>]
export function useStorage<V = any>(key: string, defaults?: V) {
  const [state, setState] = useState<V | null>(() => storage.getItem(key) ?? defaults)

  const setValue = (value: V | null) => {
    if (isNil(value)) {
      storage.removeItem(key)
      setState(null)
    } else {
      storage.setItem(key, value)
      setState(value)
    }
  }

  return [state, setValue] as const
}
